﻿using System;
using System.ServiceModel;
using System.Collections.Generic;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using SSSToolbox;

namespace CRMToolbox
{
    public class ProfilerMain : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
           
            ITracingService tracingService =
                (ITracingService)serviceProvider.GetService(typeof(ITracingService));

           
            IPluginExecutionContext context = (IPluginExecutionContext)
                serviceProvider.GetService(typeof(IPluginExecutionContext));

            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

           
            if (context.InputParameters.Contains("Target") &&
                context.InputParameters["Target"] is Entity)
            {
               
                Entity entity = (Entity)context.InputParameters["Target"];

                if (entity.LogicalName != "crmtb_profiler")
                    return;

                try
                {
                   if (entity.Attributes.Contains("crmtb_clearresults"))
                    {
                        if ((bool)entity["crmtb_clearresults"] == true)
                        {
                            EntityCollection results = GetResults(service, context);
                            DeleteResults(results, service);
                            entity["crmtb_clearresults"] = false;
                            service.Update(entity);
                        }
                    }
                    else
                    {
                        return;
                    }

                }
                catch (FaultException<OrganizationServiceFault> ex)
                {
                    throw new InvalidPluginExecutionException("An error occurred in the Profiler plug-in.", ex);
                }

                catch (Exception ex)
                {
                    tracingService.Trace("Profiler Plugin: {0}", ex.ToString());
                    throw;
                }
            }
        }

        private void DeleteResults(EntityCollection results, IOrganizationService service)
        {
            foreach(var i in results.Entities)
            {
                service.Delete("crmtb_profilerdata", i.Id);
            }
        }

        private EntityCollection GetResults(IOrganizationService service, IPluginExecutionContext context)
        {
            QueryByAttribute query = new QueryByAttribute("crmtb_profilerdata")
            {
                ColumnSet = new ColumnSet("crmtb_profilerid")
            };
            query.Attributes.AddRange("crmtb_profilerid");
            query.Values.AddRange(context.PrimaryEntityId);

            EntityCollection results = service.RetrieveMultiple(query);

            return results;
        }
    }
}